package com.ihr360.insurance.eventhandler;

import com.ihr360.event.annonation.RestEventListener;
import com.ihr360.insurance.model.dto.benefits.MandatoryBenefitsType;
import com.ihr360.insurance.service.MandatoryBenefitsTypeService;
import com.ihr360.validation.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Stone.Shi
 * @description
 * @date 2018-03-20 18:25:47.
 */
@Component
public class MandatoryBenefitsTypeRestEventListener implements RestEventListener<MandatoryBenefitsType, Long> {

    private static final String ERROR_NAME_EMPTY = "类型名称不能为空";
    private static final String NAME_EMPTY_INFO = "该类型名称已存在，请填写其他值";

    @Autowired
    private MandatoryBenefitsTypeService service;

    @Override
    public void beforeCreate(MandatoryBenefitsType mandatoryBenefitsType) {
        String name = mandatoryBenefitsType.getName();
        ValidationUtils.rejectIfEmpty(name, "", ERROR_NAME_EMPTY);
        boolean typeNameExisted = service.isTypeNameExisted(name);
        if (typeNameExisted) {
            ValidationUtils.reject("", NAME_EMPTY_INFO);
        }
    }

    @Override
    public void beforeUpdate(Long id, Map<String, Object> source, MandatoryBenefitsType mandatoryBenefitsType) {
        if (source.containsKey(MandatoryBenefitsType.Field.name)) {
            Object nameObject = source.get(MandatoryBenefitsType.Field.name);
            ValidationUtils.rejectIfEmpty(nameObject, "", ERROR_NAME_EMPTY);
            String name = String.valueOf(nameObject);
            if (!name.equals(mandatoryBenefitsType.getName())) {
                boolean typeNameExisted = service.isTypeNameExisted(name);
                if (typeNameExisted) {
                    ValidationUtils.reject("", NAME_EMPTY_INFO);
                }
            }
        }
    }
}
